﻿/// <reference path="jquery.min.js" />
/// <reference path="jquery.tools.min.js" />
/// <reference path="app.js" />
/// <reference path="page.js" />

(function (jQuery, window, app, page) {
    var $ = jQuery;
    var ps = $(".psui");

    var MIN_USER = 3;
    var MAX_USER = 5;

    if (ps.length < 1) {
        return;
    }

    ps.tax = {
        ref: {
            租金: 0,
            从业人员: [],
            折旧费: 0,
            电费: 0,
            水费: 0,
            燃气费: 0
        },

        i: function (field) {
            return parseInt(ps.find("[name=" + field + "]").val()) || 0;
        },

        f: function (field) {
            return parseFloat(ps.find("[name=" + field + "]").val()) || 0.0;
        },

        合计租金: function () {
            return this.f("经营面积") * this.f("单位面积租金");
        },
        合计折旧费: function () {
            return this.f("经营面积") * this.f("单位面积装修折旧费");
        },
        人员工资: function () {
            var t = ps.find(".em_area");
            var total = 0.0;
            t.find("tr:not(:first)").each(function () {
                var p = parseInt($(this).find("[name=人数]").val()) || 0;
                var s = parseFloat($(this).find("[name=工资]").val()) || 0.0;
                total += p * s;
            });
            return total;
        },
        result: function () {
            var 费用 = this.f("每月平均采购成本")
                + this.合计租金() + this.合计折旧费() + this.人员工资()
                + this.f("电费") + this.f("水费") + this.f("燃气费 ")
                + this.f("物业管理费") + this.f("其他费用");
            var 成本利润率 = (this.ref.成本利润率 || 0.0) / 100;
            var 营业税率 = (this.ref.营业税率 || 0.0) / 100;
            var 经营系数 = ps.find(".ps_area select[name=经营系数] option:selected").val() || 1.0;
            return (费用 * (1 + 成本利润率) / (1 - 营业税率) + this.f("设备定额") * this.f("设备数量")) * 经营系数;
        },
        config: function () {
            var ref = this.ref;
            var warn = this.warn;
            page.content.find(".ps_area td[field]").each(function () {
                var field = $(this).attr("field");
                var tax = {
                    ref: ref[field] || 0,
                    warn: warn[field] || 0
                };

                if (!tax.ref || !tax.warn) { return; }
                $(this).data("tax", tax);
            });
        },

        configEm: function (jEmArea) {
            var ref = this.ref;
            var warn = this.warn;
            jEmArea.find("tr:not(:first)").each(function () {
                var code = $(this).find("input[name=职业]").val();
                var tax = {
                    ref: ref.从业人员[code] || 0,
                    warn: warn.从业人员[code] || 0
                };

                if (!tax.ref || !tax.warn) { return; }
                $(this).data("tax", tax);
            });
        }
    };

    // 输入框事件集
    $.extend(ps, {
        configPsInput: function (input) {
            var td = input.parent("td");
            var tax = td.data("tax");
            this.configInput(input, tax);
        },

        configEmInput: function (input) {
            var tr = input.parentsUntil("tr").parent("tr");
            var tax = tr.data("tax");
            this.configInput(input, tax);
        },

        configInput: function (input, tax) {
            if (!input || !tax) {
                return;
            }

            input.unbind("focus").focus(function () {
                var tip = ps.find(".tax_tip");
                if (tip.length < 1) {
                    tip = $("<div>").addClass("tax_tip")
                    .css({
                        "width": "120px",
                        "padding": "5px",
                        "position": "absolute",
                        "display": "inline-block",
                        "color": "white",
                        "background": "#0B4482",
                        "border": "1px solid #90AFD1",
                        "line-height": "20px",
                        "height": "40px"
                    }).appendTo(ps);
                }
                tip.html("参考值：" + tax.ref + "<br/>预警值：" + tax.warn);
                var td = $(this).parent("td");
                var p = td.position();
                tip.css({
                    top: (p.top - 50) + "px",
                    left: p.left + "px"
                }).show();
                ps.f = true;
            }).unbind("blur").blur(function () {
                var v = Number($(this).val());
                log.debug(v, tax.warn);
                if (!!v && v < tax.warn) {
                    $(this).parent("td").addClass("error");
                } else {
                    $(this).parent("td").removeClass("error");
                }

                ps.f = false;
                setTimeout(function () {
                    if (!ps.f) {
                        ps.find(".tax_tip").hide();
                    }
                }, 200);
            });
        }
    });

    $.extend(ps, {
        onLoadData: function () {
            if (!!page.config.events.loadDataFailed) {
                page.applyUrl(page.makeUrl({
                    "view": "add"
                }));
                return;
            }

            if (!!this.loadedData) {
                return;
            }

            this.loadWarnData();

            // 附加配置对象
            page.content.find("td[field]").each(function () {
                var name = $(this).attr("field");
                if (!name) { return; }
                var f = page.config.fields[name];
                if (!f) { return; }
                f.grid.configTd($(this), true);
            });

            this.find("td:not(:has(:input))").addClass("readonly");
            this.find(".base_area,.ps_area,.em_area").show();

            this.loadEmployee();
        },

        loadWarnData: function () {
            var me = this;
            app.ajaxXml("core/bll/评税信息.ashx", {
                fi_act: "GetAlarmInfo",
                "行业细目代码": page.edit.data.find("行业细目代码").text(),
                "纳税人代码": page.id()
            }, function (xml) {
                var r = me.parseTaxReference(xml);
                $.extend(ps.tax, r);
                ps.tax.config();
            });
        },

        parseTaxReference: function (xml) {
            var jXml = xml instanceof jQuery ? xml : $(xml);
            var 参考 = {
                单位面积租金: parseFloat(jXml.find("单位面积租金参考").text() || 0),
                从业人员: {},
                单位面积装修折旧费: parseFloat(jXml.find("单位面积装修折旧费参考").text() || 0),
                电费: parseFloat(jXml.find("单位面积电费参考").text() || 0),
                水费: parseFloat(jXml.find("单位面积水费参考").text() || 0),
                燃气费: parseFloat(jXml.find("单位面积燃气费参考").text() || 0),
                成本利润率: parseFloat(jXml.find("成本利润率").text() || 0),
                营业税率: parseFloat(jXml.find("营业税率").text() || 0)
            };
            var 预警 = {
                单位面积租金: parseFloat(jXml.find("单位面积租金预警").text() || 0),
                从业人员: {},
                单位面积装修折旧费: parseFloat(jXml.find("折旧费预警").text() || 0),
                电费: parseFloat(jXml.find("电费预警").text() || 0),
                水费: parseFloat(jXml.find("水费预警").text() || 0),
                燃气费: parseFloat(jXml.find("燃气费预警").text() || 0)
            };

            jXml.find("sub_data").each(function () {
                var item = $(this);
                var code = item.find("从业人员代码").text();
                参考.从业人员[code] = item.find("每月平均工资参考").text();
                预警.从业人员[code] = item.find("工资预警").text();
            });

            return {
                ref: 参考,
                warn: 预警
            };
        },

        loadEmployee: function () {
            var me = this;
            app.loading.show("正在加载从业人员信息...");
            app.ajaxXml("core/bll/评税信息.ashx", {
                fi_act: "GetEmployee",
                "纳税人代码": page.id()
            }, function (xml) {
                var jXml = !xml ? null : $(xml);
                if (jXml == null || jXml.find("code").text() !== "0") {
                    alert("加载从业人员信息时发生错误");
                    return;
                }

                var jEmArea = ps.find(".em_area");
                var td = function (obj, field, type) {
                    var jTd = $("<td>").addClass("readonly align_right");
                    jTd.text(obj);
                    if (!!field) {
                        jTd.attr("field", field).data("config", {
                            isReadonly: function () { return false; },
                            type: type || "number",
                            name: field,
                            tip: {}
                        }).data("value", obj);
                    }
                    return jTd;
                };

                jEmArea.find("tr:not(:first)").remove();
                jXml.find("datas > data").each(function () {
                    var jData = $(this);
                    var code = jData.find("职业代码").text() || "";
                    $("<tr>").append(td(code).append($("<input type='hidden' name='职业'>").val(code)))
                        .append(td(jData.find("职业名称").text() || ""))
                        .append(td(jData.find("从业人员人数").text() || 0, "人数"))
                        .append(td(jData.find("从业人员平均工资").text() || 0, "工资", "decimal"))
                        .appendTo(jEmArea);
                });
                ps.tax.configEm(jEmArea);
                app.loading.hide();
                me.loadedData = true;
                me.prepareEditable();
            });
        },

        bindOnCloseOperator: function (sender) {
            sender.unbind("click").click(function () {
                var jOp = $(this).parent();
                var code = jOp.find(".code").text();
                app.ajaxXml("core/bll/税务机关和人员.ashx", {
                    fi_act: "DeleteUser",
                    "税务人员代码": code
                }, function (xml) {
                    if (!xml || $(xml).find("code").text() !== "0") {
                        alert("注销用户时发生错误: " + $(xml).find("message").text());
                        return;
                    }

                    var users = ps.getUsers(xml);
                    log.info(users);
                    ps.resetOperators(users);
                });
            });
            return sender;
        },
        bindOnTaxFocus: function (sender) {
            sender.unbind("focus.tax").bind("focus.tax", function () {
                ps.find(".ps_area td[field=电子评税额]").text(ps.tax.result());
            });
        },

        addOperator: function (code, name) {
            $("<div>").addClass("optr_item optr")
                .append($("<div>").addClass("code").text(code))
                .append($("<div>").addClass("name").text(name))
                .append(this.bindOnCloseOperator($("<a class='close'>×</a>")))
                .insertBefore(this.find(".optr_add"));
            this.find(".optr_loading").hide();
            if (this.find(".optr_area > .optr_item > .code").length >= MAX_USER) {
                this.find(".optr_add").hide();
            }
        },
        resetOperators: function (users) {
            this.find(".optr_add").siblings().remove();
            var me = this;
            $.each(users, function (i, item) {
                me.addOperator(item.code, item.name);
            });
            this.prepareEditable();
        },

        getUsers: function (xml) {
            if (!xml) {
                return [];
            }

            var jXml = xml instanceof jQuery ? xml : $(xml);
            var users = [];
            jXml.find("datas > data").each(function () {
                users.push({
                    code: $(this).children("CODE").text(),
                    name: $(this).children("NAME").text(),
                    toString: function () {
                        return this.code + ":" + this.name;
                    }
                });
            });
            return users;
        },

        loadVerifiedUsers: function () {
            app.ajaxXml("core/bll/税务机关和人员.ashx", {
                fi_act: "GetVerifiedUsers"
            }, function (xml) {
                var users = ps.getUsers(xml);
                ps.resetOperators(users);
            });
        },

        isEditable: undefined,
        prepareEditable: function () {
            var optrs = ps.find(".optr");
            if (optrs.length >= MIN_USER) {
                this.makeEditable();
            } else {
                this.makeEditless();
            }
        },

        makeEditable: function () {
            if (this.isEditable === true) {
                return;
            }

            if (!!this.loadedData) {
                this.needEditable = true;
                page.edit.makeEditable(this.find(".em_area,.ps_area"));
                this.needEditable = false;
                ps.find(".em_area,.ps_area")
                    .find("td:has(:input):not(:has(input:hidden))")
                    .removeClass("readonly")
                    .find(":input").removeClass("readonly");
                ps.find(".em_area tr").find("input:last").each(function () {
                    ps.configEmInput($(this));
                });
                ps.find(".ps_area input").each(function () {
                    ps.configPsInput($(this));
                });
                ps.bindOnTaxFocus(ps.find(".ps_area input[name=执行定额]"));

                $("input[name=定额执行日期]").makeDateInput();
                $("input[name=定额截止日期]").makeDateInput();

                var check = function () {
                    var begin = $("input[name=定额执行日期]");
                    var end = $("input[name=定额截止日期]");
                    if (begin.length == 0 || end.length == 0) { return; }

                    if (!begin.val()) {
                        end.parent("td").removeClass("error");
                    } else if (end.val() < begin.val()) {
                        end.parent("td").addClass("error");
                    } else {
                        end.parent("td").removeClass("error");
                    }

                    setTimeout(check, 200);
                };
                check();

                this.isEditable = true;
            }
        },

        makeEditless: function () {
            if (this.isEditable === false) {
                return;
            }

            var psArea = this.find(".em_area,.ps_area");
            psArea.find("td").each(function () {
                if ($(this).is(":has(input:hidden)")) {
                    return;
                }
                var jTd = $(this);
                jTd.addClass("readonly").text(jTd.find(":input").val());
            });
            this.isEditable = false;
        }
    });

    $.extend(ps, {
        init: function () {
            app.validator.cfgVerify(ps.find("#纳税人代码"));
            ps.find("#纳税人代码").keypress(function (e) {
                if (e.keyCode === 13) {
                    var code = $(this).val();
                    if (!code) {
                        return;
                    }

                    ps.loadedData = false;
                    page.applyUrl(page.makeUrl({
                        "view": "edit",
                        "id": code
                    }));
                }
            });

            this.loadVerifiedUsers();
            this.initUserArea();
            if (/edit/i.test(page.view())) {
                this.initEdit();
            }
        },
        initUserArea: function () {
            var me = this;
            log.debug(this.find(".optr_add").length);
            this.find(".optr_area").disableSelect();
            this.find(".optr_add").unbind("click").click(function () {
                app.dialog.login(function (xml) {
                    var users = me.getUsers(xml);
                    if (!users || users.length < 1) {
                        alert("验证失败");
                    } else {
                        ps.resetOperators(users);
                    }
                });
            });
        },
        initEdit: function () {
            log.info("initEdit", page.config.events.needLoadData);
            if (!!page.config && !!page.config.events.needLoadData) {
                this.onLoadData();
            }
        }
    });

    window.pingshui = window.$ps = ps;
    ps.init();
})(jQuery, window, app, page);
